package com.example.demo.modules.user.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.example.demo.modules.user.dto.UserDTO;
import com.example.demo.modules.user.service.UserService;

/**
 * 用户管理页面控制器
 * 处理与用户管理相关的页面请求
 */
@Controller
@RequestMapping("/admin/users")
public class UserViewController {

    @Autowired
    private UserService userService;
    
    /**
     * 用户列表页面
     */
    @GetMapping
    public String listUsers(Model model, @RequestParam(defaultValue = "") String keyword) {
        model.addAttribute("users", userService.search(keyword));
        model.addAttribute("keyword", keyword);
        return "admin/user/list";
    }
    
    /**
     * 用户添加页面
     */
    @GetMapping("/add")
    public String addUserForm(Model model) {
        model.addAttribute("user", new UserDTO());
        return "admin/user/edit";
    }
    
    /**
     * 用户编辑页面
     */
    @GetMapping("/edit/{id}")
    public String editUserForm(@PathVariable Long id, Model model) {
        model.addAttribute("user", userService.findById(id));
        return "admin/user/edit";
    }
    
    /**
     * 保存用户
     */
    @PostMapping("/save")
    public String saveUser(@ModelAttribute UserDTO userDTO, RedirectAttributes redirectAttributes) {
        try {
            if (userDTO.getId() == null) {
                userService.save(userDTO);
                redirectAttributes.addFlashAttribute("message", "用户添加成功");
            } else {
                userService.update(userDTO);
                redirectAttributes.addFlashAttribute("message", "用户更新成功");
            }
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("error", "操作失败: " + e.getMessage());
        }
        
        return "redirect:/admin/users";
    }
    
    /**
     * 删除用户
     */
    @GetMapping("/delete/{id}")
    public String deleteUser(@PathVariable Long id, RedirectAttributes redirectAttributes) {
        try {
            userService.delete(id);
            redirectAttributes.addFlashAttribute("message", "用户删除成功");
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("error", "删除失败: " + e.getMessage());
        }
        
        return "redirect:/admin/users";
    }
} 